


class IntegerField < StringField

  def class_body
    if name && name.length > 0
      "property :#{name}, Integer\n"#+
      #"attr_reader :#{name}\n"+
      #"def #{name}= v\n  attribute_set(:#{name}, v)\nend"
    end
  end

  def validate value
    value.to_i
  end

  def thingswecanadd
    [TextThing]
  end


  class Test < FwTest
    def test_class_body
      nf = IntegerField.new('price')
      body = nf.class_body.split("\n")
      eq body[0], 'property :price, Integer'
      #eq body[1], 'attr_reader :price'
    end

    def test_generate_no_code_when_name_empty
      eq IntegerField.new.class_body, nil
    end

    def test_generated_input_has_the_right_value
      field = IntegerField.new()
      field.name = 'sides'
      field.value = 5
      field.child = InputThing.new
      eq field.creator(Event.new()).value, "5"
        "Element didn't create input of value 5"
    end

    def test_generated_form_has_the_right_value
      DataMapper.setup(:test, :adapter => 'in_memory')
      repository(:test) {
        template = ContentTemplate.new
        template.template_class = 'Cube'
        template.add IntegerField.new(:sides)
        template.save

        cube = template.clone_thing

        cube.sides = 5
        form_fields = cube.creator(Event.new(nil, {:params => {}}))
        assert form_fields.match(/<input(.*)value="5"(.*)\/>/)#, form_fields
          #"Form didn't contain field with input of value 5"
      }
    end

    def test_recieve_integration
      DataMapper.setup(:test, :adapter => 'in_memory')
      repository(:test) {
        template = ContentTemplate.new
        template.template_class = 'Cube'
        template.add IntegerField.new(:sides)
        template.save

        cube = template.clone_thing

        cube.sides = 5
        form_fields = cube.creator(Event.new(nil, {:params => {}}))
        assert input = form_fields.match(/<input(.*)value="5"(.*)\/>/),
          "Form didn't contain field with input of value 5"
        assert input_name = input[0].match(/name="([^"]*)"/)[1]

        params = { input_name => '6' }

        cube.recieve(RequestEvent::Mock.new({'params' => params}))

        eq cube.sides, 6, "Recieving #{params.inspect} should have changed sides to 6."
      }
    end
  end
end